package cn.ronghuanet.auth.service.impl;

import cn.ronghuanet.auth.domain.Permission;
import cn.ronghuanet.auth.domain.Role;
import cn.ronghuanet.auth.domain.RolePermission;
import cn.ronghuanet.auth.dto.RoleDto;
import cn.ronghuanet.auth.mapper.PermissionMapper;
import cn.ronghuanet.auth.mapper.RolePermissionMapper;
import cn.ronghuanet.auth.service.IRoleService;
import cn.ronghuanet.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2024-04-07
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void saveOrUpdate(RoleDto roleDto) {
        Role role = roleDto.getRole();
        if (role.getId()!=null){
            super.update(role);
        }else {
            super.save(role);
        }
        //维护中间表数据
        /*
            新增:
                添加数据,把新增数据和选中的权限数据写入到关联表就Ok
            修改:
                前端选择的数据      数据库有的数据
                  1234                3456
                  12                  123
                  12346               1234
            把原来的全部删除,重新维护关联关系
         */
        //1.删除角色对应权限数据
        rolePermissionMapper.deleteByRoleId(role.getId());
        //2.重新维护关联关系
        //2.1查询出用户选择的权限id的数据
        List<Permission> permissions = permissionMapper.queryByIds(roleDto.getPermissionIds());

        List<RolePermission> list = new ArrayList<>();
        for (Permission permission : permissions) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(permission.getId());
            rolePermission.setPermissionSn(permission.getSn());
            list.add(rolePermission);
        }

        rolePermissionMapper.batchSave(list);



    }

    @Override
    public List<Long> getPermsssionId(Long id) {
        return rolePermissionMapper.getPermsssionId(id);
    }
}
